package org.lqk.pool.socket2;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA. User: hadoop Date: 13-10-18 Time: 上午10:46
 */
public class GenericSocketConnection implements SocketConnection {

	static final Logger logger = Logger.getLogger(GenericSocketConnection.class.getName());
	private Socket socket;

	private DataInputStream in;
	private DataOutputStream out;

	private String host;
	private int port;

	public GenericSocketConnection(String host, int port) throws IOException {
		this(host, port, 5000);
	}

	public GenericSocketConnection(String host, int port, int soTimeout) throws IOException {
		this.host = host;
		this.port = port;
		this.socket = new Socket(this.host, this.port);
		this.socket.setSoTimeout(soTimeout);
		this.in = new DataInputStream(socket.getInputStream());
		this.out = new DataOutputStream(socket.getOutputStream());
	}

	@Override
	public void write(byte[] b) throws IOException {
		out.write(b);
		out.flush();
	}

	@Override
	public DataOutputStream dataInputStream() {
		return this.dataInputStream();
	}

	@Override
	public void destory() {
		IOUtils.closeQuietly(in);
		IOUtils.closeQuietly(out);
		IOUtils.closeQuietly(socket);
		this.out = null;
		this.in = null;
		this.socket = null;
	}

	@Override
	public boolean isClosed() {
		return this.socket.isClosed();
	}

	@Override
	public Socket socket() {
		return this.socket;
	}
}
